package com.lyy.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lyy.handler.BusinessException;
import com.lyy.response.ResultCode;
import com.lyy.system.entity.Department;
import com.lyy.system.mapper.DepartmentMapper;
import com.lyy.system.service.DepartmentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lyy
 * @since 2022-05-15
 */
@Service
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department> implements DepartmentService {

    @Override
    public List<Department> findDeptAndCount() {
        return this.baseMapper.findDeptAndCount();
    }

    @Override
    public IPage<Department> findDeptPage(Page<Department> page, QueryWrapper<Department> wrapper) {
        Page<Department> department =this.baseMapper.selectPage(page,wrapper);
        return department;
    }

    @Override
    public void addDept(Department department) {
        //判断部门名称是否存在
        String deptName=department.getName();
        QueryWrapper<Department> wrapper =new QueryWrapper<>();
        wrapper.eq("name",deptName);
        Integer count =this.baseMapper.selectCount(wrapper);
        if (count!=0){
            throw new BusinessException(ResultCode.DEPARTMENT_ALREADY_EXIST.getCode(),
                    ResultCode.USER_ACCOUNT_ALREADY_EXIST.getMessage());
        }
        this.baseMapper.insert(department);
    }

    @Override
    public void updataDepat(Department department) {
        String deptName= department.getName();
        QueryWrapper<Department> wrapper = new QueryWrapper<>();
        wrapper.eq("name",deptName);
        Integer count =this.baseMapper.selectCount(wrapper);
        if (count!=0){
            throw new BusinessException(ResultCode.DEPARTMENT_ALREADY_EXIST.getCode(),
                    ResultCode.USER_ACCOUNT_ALREADY_EXIST.getMessage());
        }
        this.baseMapper.updateById(department);

    }

    @Override
    public void deleteDeprById(Long id) {
        this.baseMapper.deleteById(id);
    }
}
